import { Drawer, Button, Space } from "antd";
import CloudTable from "@/component/CloudTable";
import { useEffect } from "react";

/**
 * save 保存关联关系
 * tableProps 表格属性
 * @returns 
 */
const TableDrawer = ({ props = {} }) => {

    // 表格属性
    const { title, width, visible, row, selected, onReload, resetData, resetSelected, isOpenDialog, isPage, onCallback } = props;

    // 表格工具栏 -> 保存按钮
    props.tools = () => {
        return (
            <Space>
                <Button type="primary" onClick={onSaveRelationHandler} >保存</Button>
            </Space>
        );
    }

    // 初始化选中行
    const selectedRows = (result) => {
        if (isPage) {
            let page = {
                current: result?.pageNo || 1,
                size: result?.pageSize || 10,
                total: result?.total || 0,
            }
            resetData(result?.records, page);
        } else {
            resetData(result);
        }
        resetSelected(selectedKeys(result));
    }

    const selectedKeys = (rows) => {
        let keys = [];
        if (rows?.length > 0) {
            rows.forEach(each => {
                if (each.children) {
                    let subKeys = selectedKeys(each.children);
                    keys = [...keys, ...subKeys];
                }
                if (each.isBind) {
                    keys.push(each.id);
                }
            });
        }
        return keys;
    }

    // 保存关联关系
    const onSaveRelationHandler = () => {
        let param = {
            id: row,
            detail: selected,
        }
        onCallback(param);
    }

    useEffect(() => {
        if (visible) {
            onReload(row, selectedRows);
        }
    }, [visible]);

    return (
        <Drawer width={width + 100} title={title} open={visible} onClose={() => isOpenDialog()}>
            <CloudTable props={props} />
        </Drawer>
    );
}

export default TableDrawer;